<template>
  <div class='container'>
    <el-dialog title="新增标签" :visible="dialogFormVisible" width='400px' @close='handleClose' @open='handleOpen' class="addWin">
      <div class="addDialog">
        <el-form :model="queryParams" ref="addForm" :rules="rules">
          <el-form-item label="所属学科" prop="subjectID">
            <el-select v-model="queryParams.subjectID" placeholder="请选择" size="small" class="select">
              <el-option v-for="obj in subjectList" :key="obj.id" :label="obj.subjectName" :value="obj.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称" prop="tagName">
            <el-input v-model="queryParams.tagName" autocomplete="off" placeholder="请输入标签名称" size="small" class="tagNameIpt" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <div class="btn">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add } from '@/api/hmmm/tags'
import { list } from '@/api/hmmm/subjects'

export default {
  name: 'tags-add',
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      queryParams: {
        subjectID: '',
        tagName: ''
      },
      subjectList: [],
      // 表单验证
      rules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: ['blur', 'change'] }
        ],
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    handleClose () {
      this.$emit('update:dialogFormVisible', false)
      this.$refs.addForm.resetFields()
    },
    handleSubmit () {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        try {
          const ret = await add(this.queryParams)
          if (ret.status === 200) {
            this.$emit('update:dialogFormVisible', false)
            this.$parent.loadTagsList()
            this.$message.success('标签添加成功')
          }
        } catch {
          this.$message.error('标签添加失败')
        }
      })
    },
    async handleOpen () {
      this.$nextTick(() => {
        this.$refs.addForm.resetFields()
        // this.$refs.addForm.clearValidate()
      })
      const ret = await list()
      this.subjectList = ret.data.items
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  .addWin {
    height: 600px;
    .dialog-footer {
      position: relative;
      margin-top: 40px;
      .btn {
        position: absolute;
        right: 1px;
        bottom: 4px;
        width: 160px;
      }
    }
    .addDialog /deep/ .el-input__inner {
      width: 100%;
    }
    .select {
      width: 100%;
    }
    .tagNameIpt {
      width: 100%;
    }
  }
}
</style>
